import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { routerRedux, Link } from 'dva/router';
import {
  Row, Col, Card, Form, Input, Select, Icon,
  Button, Dropdown, Menu, InputNumber,
  DatePicker, Modal, message, Badge,
  Divider, Tag, Table,
} from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './CreditReportingQueries.less';

/*
 申请管理征信查询界面
*/

const FormItem = Form.Item;
const { Option } = Select;

const { MonthPicker, RangePicker } = DatePicker;

const relation = ['申请人', '共同还款人', '担保人'];
const stateCredit = ['未征信', '已征信'];
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');
@connect(({ queries }) => ({
  queries,
  // loading: loading.models.rule,
}))
@Form.create()
export default class CreditReportingQueries extends PureComponent {
  state = {
    startTime: '',
    endTime: '',
    startTimeArray: [],
    dataTimeFlag: false,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'queries/fetch',
      payload: {
        offset: 0,
        limit: 10,
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      offset: (pagination.current - 1) * pagination.pageSize,
      limit: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (params.state) {
      const p = params.state.split(",")
      if (p.length > 1) {
        dispatch({
          type: 'queries/fetch',
          payload: {
            offset: 0,
            limit: 10,
          },
        });
      } else {
        dispatch({
          type: 'queries/fetch',
          payload: params,
        });
      }
    } else {
      dispatch({
        type: 'queries/fetch',
        payload: params,
      });
    }
  }

  handleSearch = () => {
    const { validateFieldsAndScroll } = this.props.form;
    validateFieldsAndScroll((error, values) => {
      if (!error) {
        // console.log("qqqqqq")
        // console.log(values)
        this.props.dispatch({
          type: 'queries/fetch',
          payload: {
            custName: values.custname,
            createTimeBegin: this.state.startTime,
            createTimeEnd: this.state.endTime,
          },
          callback: () => {
            this.props.dispatch({
              type: 'queries/fetch',
              payload: {
                offset: 0,
                limit: 10,
              },
            });
          },
        })
        // this.props.form.resetFields();
      }
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      dataTime: [],
      value: '',
      dataTimeFlag: false,
      startTimeArray: [],
      startTime: '',
      endTime: '',
    });
    dispatch({
      type: 'queries/fetch',
      payload: {
        offset: 0,
        limit: 10,
      },
    });
  }

  handleStartTimeChange = (dates, dateString) => {
    // console.log(dates)
    this.setState({
      startTimeArray: dates,
      startTime: dates[0],
      endTime: dates[1],
    });
  }


  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={10} sm={24}>
            <FormItem label="客户名称">
              {getFieldDecorator('custname')(
                <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>
          <Col md={10} sm={24}>
            <FormItem label="创建时间">
              {getFieldDecorator('createTime')(
                <div>
                  <RangePicker
                    style={{ width: '100%' }}
                    allowClear={true}
                    showToday={true}
                    onChange={this.handleStartTimeChange}
                    value={[
                      this.state.dataTimeFlag ? null : this.state.startTime,
                      this.state.dataTimeFlag ? null : this.state.endTime
                    ]}
                    showTime={{ hideDisabledOptions: true }}
                    format="YYYY-MM-DD HH:mm:ss"
                  />
                </div>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <p style={{ textAlign: 'right' }} className={styles.submitButtons}>
            <Button type="primary" htmlType="submit">搜索</Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
          </p>
        </Row>

      </Form>
    );
  }

  columns = [{
    title: '客户名称',
    dataIndex: 'custname',
    key: 'custname',
  }, {
    title: '合作机构名称',
    dataIndex: 'orgName',
    key: 'orgName',
  }, {
    title: '关系类型',
    dataIndex: 'relation',
    key: 'relation',
    render(val) {
      return relation[val];
    },
  }, {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  }, {
    title: '状态',
    dataIndex: 'state',
    key: 'state',
    filters: [
      {
        text: stateCredit[0],
        value: 0,
      },
      {
        text: stateCredit[1],
        value: 1,
      },
    ],
    render(val) {
      return stateCredit[val];
    },
  }, {
    title: '操作',
    dataIndex: 'id',
    key: 'id',
    render: (text, record) => (
      // console.log(record.id),
      <Fragment>
        <Link to={`/reporting/inquiry-details?id=${record.id}`}>详情</Link>
      </Fragment>
    ),
  }];

  render() {
    const { queries: { reportingList, page, loading } } = this.props;

    return (
      <PageHeaderLayout
        title="征信查询"
      >
        {/* {JSON.stringify(reportingList)} */}
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              {this.renderSimpleForm()}
            </div>

            <Table
              dataSource={reportingList}
              columns={this.columns}
              loading={loading}
              pagination={page}
              bordered
              rowKey="id"
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
